import React, {useRef} from 'react';
//引入axios配置全局axios
import axios from './service/request'


const CameraComponent = () => {

    let interval = null
    let color = ['orange', 'red', 'yellow', 'green', 'pink']
    let rand = 0;
    const cameraVideoRef = useRef(null);
    const cameraCanvasRef = useRef(null);

    function getNextColor() {
        rand = (rand + 1) % 5
        return color[rand]
    }

    function successFunc(mediaStream) {
        const video = cameraVideoRef.current;
        // const video = document.getElementById('cameraVideo') as HTMLVideoElement;
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in video) {
            video.srcObject = mediaStream;
        }
        video.onloadedmetadata = () => {
            video.play();
        };
    }

    function errorFunc(err) {
        console.log(`${err.name}: ${err.message}`);
        // always check for errors at the end.
    }

    // 启动摄像头
    const openMedia = () => { // 打开摄像头
        let img = document.getElementById('img')
        img.style.display = 'none'

        let vi = document.getElementById('cameraVideo')
        vi.style.display = 'block'

        let bg = document.getElementById('background')
        interval = setInterval(() => {
            bg.style.backgroundColor = getNextColor()
        }, 1000)

        const opt = {
            audio: false,
            video: {
                width: 300,
                height: 300,
            }
        };
        navigator.mediaDevices.getUserMedia(opt).then(successFunc).catch(errorFunc);
    };
    // 关闭摄像头
    const closeMedia = () => {
        document.getElementById('cameraVideo').style.display = 'none'
        document.getElementById('cameraCanvas').style.display = 'none'
        clearInterval(interval)
        document.getElementById('imgTag').src = '/logo192.png'
        document.getElementById('img').style.display = 'block'

        // const video = document.getElementById('cameraVideo') as HTMLVideoElement;
        const video = cameraVideoRef.current;
        const stream = video.srcObject;
        if ('getTracks' in stream) {
            const tracks = stream.getTracks();
            tracks.forEach(track => {
                track.stop();
            });
        }
    };

    const getImg = () => { // 获取图片资源
        // const video = document.getElementById('cameraVideo') as HTMLVideoElement;
        // const canvas = document.getElementById('cameraCanvas') as HTMLCanvasElement;
        const video = cameraVideoRef.current;
        const canvas = cameraCanvasRef.current;
        if (canvas == null) {
            return;
        }
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight); // 把视频中的一帧在canvas画布里面绘制出来
        const imgStr = canvas.toDataURL(); // 将图片资源转成字符串
        const base64Img = imgStr.split(';base64,').pop(); // 将图片资源转成base64格式
        const imgData = {
            base64Img
        };
        // closeMedia(); // 获取到图片之后可以自动关闭摄像头
        return imgData;
    };


    const saveImg = () => { // electron项目保存到本地
        let userName = document.getElementById('input').value
        let group = document.getElementById('select').value
        clearInterval(interval)
        const data = getImg();
        console.log(data)

        axios.put("/face/addUser", {
            'img': data.base64Img,
            'userGroup': group,
            'userName': userName
        }).then(r => {
            console.log(r)
            if (r.code === 200) {
                alert("保存成功！")
            } else {
                alert(r.msg)
            }
        }).catch(e => {
            console.log(e)
        })

        document.getElementById('input').value = ''
        // document.getElementById('imgTag').src = data.base64Img
        // 上传图片

        closeMedia()
    };
    const searchImg = () => { // electron项目保存到本地
        let group = document.getElementById('select').value
        clearInterval(interval)
        const data = getImg();
        console.log(data)

        axios.post("/face/search", {
            'img': data.base64Img,
            'userGroup': group
        }).then(r => {
            console.log(r)
            alert("欢迎回来！" + r.data)
            console.log(r)
        }).catch(e => {
            alert("陌生人！请联系管理员！")
            console.log(e)
        })


        // document.getElementById('imgTag').src = data.base64Img
        // 上传图片

        closeMedia()
    };

    return (
        <div id="background" style={{backgroundColor: 'orange'}}>
            <div style={{width: '100%', height: '100px'}}>
                <input id="input" placeholder="请输入用户名"/>
                <select id="select">
                    <option value="one">一单元</option>
                    <option value="two">二单元</option>
                </select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <button onClick={openMedia}>打开摄像头</button>
                <button onClick={saveImg}>保存</button>
                <button onClick={closeMedia}>关闭摄像头</button>
                <button onClick={searchImg}>人脸识别</button>
            </div>
            <div style={{width: '100%', height: '800px'}}>
                <video
                    id="cameraVideo"
                    ref={cameraVideoRef}
                    style={{
                        width: '300px', height: '300px', margin: '0 auto', display: 'none'
                    }}
                />
                <div id="img" style={{display: 'block'}}>
                    <img id="imgTag" width={300} height={300} src="/logo192.png" alt="imgTag"/>
                </div>
            </div>
            <canvas
                id="cameraCanvas"
                ref={cameraCanvasRef}
                width={300}
                height={300}
                style={{
                    width: '300px', height: '300px'
                }}
            />
        </div>
    )
}

export default CameraComponent
